package com.meusconcursos;

import java.util.ArrayList;

import com.meusconcursos.dto.Formacao;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;

public class FormacaoListActivity extends ListActivity {

	private class FormacaoAdapter extends ArrayAdapter<Formacao> {

		private ArrayList<Formacao> items;

		public FormacaoAdapter(Context context, int textViewResourceId,
				ArrayList<Formacao> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(android.R.layout.simple_list_item_checked, null);
			}

			Formacao formacao = items.get(position);
			if (formacao != null) {
				CheckedTextView check = (CheckedTextView) v
						.findViewById(android.R.id.text1);
				check.setChecked(formacao.isChecked());
				check.setText(formacao.getNome());
			}

			return v;

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(R.string.titulo_lista_formacao);
		setContentView(R.layout.list_formacao);

		FormacaoAdapter adapter = new FormacaoAdapter(this,
				android.R.layout.simple_list_item_checked,
				MeusConcursosActivity.dbHelper
						.getFormacoesFromCargo((String) getIntent()
								.getExtras().get("id_cargo")));

		setListAdapter(adapter);

		this.getListView().setOnItemClickListener(
				new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parentView,
							View childView, int position, long id) {

						CheckedTextView check = (CheckedTextView) childView;
						check.setChecked(!check.isChecked());
						Formacao formacao = (Formacao) parentView
								.getItemAtPosition(position);
						MeusConcursosActivity.dbHelper.configurarPlanoEstudo(
								formacao.getId(), check.isChecked());

					}

				});

	}

}
